@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)

package wang.xinqiu.mysqlcontrol.ui

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import wang.xinqiu.mysqlcontrol.data.MySQLManager
import wang.xinqiu.mysqlcontrol.data.QueryResult
import androidx.compose.foundation.combinedClickable
import androidx.compose.ui.text.style.TextOverflow

@Composable
fun TableInfoScreen(
    databaseName: String,
    tableName: String,
    mysqlManager: MySQLManager,
    onBack: () -> Unit,
    onSessionExpired: (() -> Unit)? = null
) {
    val context = LocalContext.current
    
    var tableStructure by remember { mutableStateOf<QueryResult?>(null) }
    var createTableSQL by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var selectedTab by remember { mutableStateOf(0) }
    
    LaunchedEffect(Unit) {
        isLoading = true
        errorMessage = null
        
        (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
            // 获取表结构
            val structureResult = mysqlManager.executeQuery(databaseName, "DESCRIBE `$tableName`")
            if (structureResult.isSuccess) {
                tableStructure = structureResult.getOrNull()
                
                // 获取创建表的SQL语句
                val createSQLResult = mysqlManager.executeQuery(databaseName, "SHOW CREATE TABLE `$tableName`")
                if (createSQLResult.isSuccess) {
                    val createResult = createSQLResult.getOrNull()
                    createTableSQL = createResult?.rows?.firstOrNull()?.getOrNull(1) ?: ""
                }
            } else {
                errorMessage = structureResult.exceptionOrNull()?.message
                if (errorMessage?.contains("会话已过期") == true) {
                    onSessionExpired?.invoke()
                }
            }
            
            isLoading = false
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("表信息 - $tableName") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(
                        onClick = {
                            isLoading = true
                            errorMessage = null
                            
                            (context as androidx.activity.ComponentActivity).lifecycleScope.launch {
                                val structureResult = mysqlManager.executeQuery(databaseName, "DESCRIBE `$tableName`")
                                if (structureResult.isSuccess) {
                                    tableStructure = structureResult.getOrNull()
                                    
                                    val createSQLResult = mysqlManager.executeQuery(databaseName, "SHOW CREATE TABLE `$tableName`")
                                    if (createSQLResult.isSuccess) {
                                        val createResult = createSQLResult.getOrNull()
                                        createTableSQL = createResult?.rows?.firstOrNull()?.getOrNull(1) ?: ""
                                    }
                                } else {
                                    errorMessage = structureResult.exceptionOrNull()?.message
                                    if (errorMessage?.contains("会话已过期") == true) {
                                        onSessionExpired?.invoke()
                                    }
                                }
                                isLoading = false
                            }
                        }
                    ) {
                        Icon(Icons.Default.Refresh, contentDescription = "刷新")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Tab 选择器
            TabRow(selectedTabIndex = selectedTab) {
                Tab(
                    selected = selectedTab == 0,
                    onClick = { selectedTab = 0 },
                    text = { Text("表结构") }
                )
                Tab(
                    selected = selectedTab == 1,
                    onClick = { selectedTab = 1 },
                    text = { Text("创建SQL") }
                )
            }
            
            when {
                isLoading -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
                errorMessage != null -> {
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        )
                    ) {
                        Text(
                            text = "错误: $errorMessage",
                            modifier = Modifier.padding(16.dp),
                            color = MaterialTheme.colorScheme.onErrorContainer
                        )
                    }
                }
                else -> {
                    when (selectedTab) {
                        0 -> {
                            // 表结构视图
                            tableStructure?.let { structure ->
                                 TableStructureView(structure)
                            }
                        }
                        1 -> {
                            // 创建SQL视图
                            CreateSQLView(createTableSQL)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun TableStructureView(structure: QueryResult) {
    var showContentDialog by remember { mutableStateOf(false) }
    var dialogContent by remember { mutableStateOf("") }
    var dialogTitle by remember { mutableStateOf("") }
    
    Card(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            Text(
                text = "字段信息",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            if (structure.columns.isNotEmpty() && structure.rows.isNotEmpty()) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    item {
                        LazyRow {
                            items(structure.columns.indices.toList()) { columnIndex ->
                                Column {
                                    // 表头
                                    Card(
                                        modifier = Modifier
                                            .width(120.dp)
                                            .height(48.dp)
                                            .padding(1.dp),
                                        colors = CardDefaults.cardColors(
                                            containerColor = MaterialTheme.colorScheme.primaryContainer
                                        )
                                    ) {
                                        Box(
                                            modifier = Modifier.fillMaxSize(),
                                            contentAlignment = Alignment.Center
                                        ) {
                                            Text(
                                                text = structure.columns[columnIndex],
                                                modifier = Modifier.padding(8.dp),
                                                style = MaterialTheme.typography.labelMedium,
                                                color = MaterialTheme.colorScheme.onPrimaryContainer,
                                                maxLines = 1,
                                                overflow = TextOverflow.Ellipsis
                                            )
                                        }
                                    }
                                    
                                    // 该列的所有数据
                                    structure.rows.forEachIndexed { rowIndex, row ->
                                        val cellContent = if (columnIndex < row.size) row[columnIndex] else ""
                                        
                                        Card(
                                            modifier = Modifier
                                                .width(120.dp)
                                                .height(48.dp)
                                                .padding(1.dp)
                                                .combinedClickable(
                                                    onClick = { },
                                                    onDoubleClick = {
                                                        dialogContent = cellContent
                                                        dialogTitle = "${structure.columns[columnIndex]} (第${rowIndex + 1}行)"
                                                        showContentDialog = true
                                                    }
                                                ),
                                            colors = CardDefaults.cardColors(
                                                containerColor = MaterialTheme.colorScheme.surface
                                            )
                                        ) {
                                            Box(
                                                modifier = Modifier.fillMaxSize(),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                Text(
                                                    text = cellContent,
                                                    modifier = Modifier.padding(8.dp),
                                                    style = MaterialTheme.typography.bodySmall,
                                                    fontFamily = FontFamily.Monospace,
                                                    color = MaterialTheme.colorScheme.onSurface,
                                                    maxLines = 1,
                                                    overflow = TextOverflow.Ellipsis
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                Text(
                    text = "无表结构信息",
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
    
    // 内容详情弹窗
    if (showContentDialog) {
        AlertDialog(
            onDismissRequest = { showContentDialog = false },
            title = { Text(dialogTitle) },
            text = {
                SelectionContainer {
                    Text(
                        text = dialogContent,
                        fontFamily = FontFamily.Monospace,
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            },
            confirmButton = {
                TextButton(onClick = { showContentDialog = false }) {
                    Text("关闭")
                }
            }
        )
    }
}

@Composable
fun CreateSQLView(createSQL: String) {
    Card(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            Text(
                text = "创建表的SQL语句",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            if (createSQL.isNotEmpty()) {
                SelectionContainer {
                    LazyColumn {
                        item {
                            Text(
                                text = createSQL,
                                fontFamily = FontFamily.Monospace,
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(8.dp)
                            )
                        }
                    }
                }
            } else {
                Text(
                    text = "无法获取创建SQL语句",
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}